package com.sinothk.fc.supplier.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sinothk.fc.supplier.entity.SupplierSearchKeyword;
import com.sinothk.fc.supplier.mapper.SupplierSearchKeywordMapper;
import com.sinothk.fc.supplier.service.ISupplierSearchKeywordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description: 供应商搜索关键字
 * @Author: Liangyt
 * @Date: 2022-08-13
 * @Version: V1.0
 */
@Service
public class SupplierSearchKeywordServiceImpl extends ServiceImpl<SupplierSearchKeywordMapper, SupplierSearchKeyword> implements ISupplierSearchKeywordService {

    @Override
    public IPage<SupplierSearchKeyword> searchKeywordList(Page<SupplierSearchKeyword> page, String district) {
        LambdaQueryWrapper<SupplierSearchKeyword> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(district)) {
            wrapper.likeLeft(SupplierSearchKeyword::getDistrictName, district);
        }
        wrapper.orderByDesc(SupplierSearchKeyword::getUsedTimes);
        IPage<SupplierSearchKeyword> pageData = this.page(page, wrapper);
        if (pageData == null || pageData.getSize() == 0) {
            LambdaQueryWrapper<SupplierSearchKeyword> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.orderByDesc(SupplierSearchKeyword::getUsedTimes);
            pageData = this.page(page, wrapper2);
        }
        return pageData;
    }

    @Override
    public void add(SupplierSearchKeyword supplierSearchKeyword) {
        LambdaQueryWrapper<SupplierSearchKeyword> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SupplierSearchKeyword::getKeyword, supplierSearchKeyword.getKeyword())
                .eq(SupplierSearchKeyword::getDistrictName, supplierSearchKeyword.getDistrictName());
        List<SupplierSearchKeyword> searchKeywordList = this.list(wrapper);
        if (searchKeywordList == null || searchKeywordList.size() == 0) {
            supplierSearchKeyword.setUsedTimes(1);
            this.save(supplierSearchKeyword);
        } else if (searchKeywordList.size() == 1) {
            SupplierSearchKeyword supplierSearchKeywordDb = searchKeywordList.get(0);
            int times = supplierSearchKeywordDb.getUsedTimes();
            supplierSearchKeywordDb.setUsedTimes(times + 1);
            this.updateById(supplierSearchKeywordDb);
        } else {
            // 删除异常数据
            this.remove(wrapper);
            // 新增一条
            supplierSearchKeyword.setUsedTimes(1);
            this.save(supplierSearchKeyword);
        }
    }
}
